package com.kumz.SpringMVC.controller;

import com.kumz.SpringMVC.pojo.User;
import com.kumz.SpringMVC.service.UserService;
import com.kumz.SpringMVC.tools.RandomValidateCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Author: Yunz
 * E-mail: 1603754314@qq.com
 * Date: 2022/11/28
 */

@Controller
@RequestMapping(path="/login", method={RequestMethod.POST,RequestMethod.GET})
public class LoginController {
    @Autowired
    private UserService userService;
    //后端生成的验证码（String）
    String rvc;

    @PostMapping("/doLogin")
    public String doLogin(User user, HttpServletRequest request, String vCode) {
        try {
            User u = userService.login(user);

            if (u != null) {
                if (vCode.equals(rvc)) {
                    request.getSession().setAttribute("USER_SESSION", u);
                    return "redirect:/admin/showIndex";
                } else {
                    System.out.println("验证码错误");
                    request.setAttribute("msg", "用户名或密码错误");
                    return "redirect:/login/showLogin";
                }
            }
            System.out.println("用户名或密码错误");
            request.setAttribute("msg", "用户名或密码错误");
            return "redirect:/login/showLogin";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg", "系统错误");
            return "forward:/login/showLogin";
        }
    }
    @PostMapping("/showLogin")
    public void showLogin(){ }

    @PostMapping("/logout")
    public String logout(HttpServletRequest request){
        try {
            HttpSession session = request.getSession();
            //销毁Session
            session.invalidate();
            return  "redirect:/login/showLogin";
        }catch(Exception e){
            e.printStackTrace();
            request.setAttribute("msg","系统错误");
            return  "redirect:/login/showLogin";
        }
    }

    @RequestMapping("/checkCode")
    public void checkCode(HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("image/jpeg");
        response.setHeader("pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expire", 0);

        RandomValidateCode randomValidateCode = new RandomValidateCode();
        randomValidateCode.getRandcode(request,response);
        rvc = randomValidateCode.vCode;
        System.out.println(rvc);
    }

}
